App({
  onLaunch: function () {
    if (wx.cloud) {
      wx.cloud.init({
        env: '你的云环境ID',
        traceUser: true
      })
    }
    this.db = wx.cloud.database()
    this._ = this.db.command;

    wx.getSystemInfo({
      success: e => {
        this.globalData.StatusBar = e.statusBarHeight;
        let capsule = wx.getMenuButtonBoundingClientRect();
        if (capsule) {
          this.globalData.Custom = capsule;
          this.globalData.CustomBar = capsule.bottom + capsule.top - e.statusBarHeight;
        } else {
          this.globalData.CustomBar = e.statusBarHeight + 50;
        }
      }
    })
  },

  globalData: {
    ColorList: [{
      title: '嫣红',
      name: 'red',
      color: '#e54d42'
    },
    {
      title: '桔橙',
      name: 'orange',
      color: '#f37b1d'
    },
    {
      title: '明黄',
      name: 'yellow',
      color: '#fbbd08'
    },
    {
      title: '橄榄',
      name: 'olive',
      color: '#8dc63f'
    },
    {
      title: '森绿',
      name: 'green',
      color: '#39b54a'
    },
    {
      title: '天青',
      name: 'cyan',
      color: '#1cbbb4'
    },
    {
      title: '海蓝',
      name: 'blue',
      color: '#0081ff'
    },
    {
      title: '姹紫',
      name: 'purple',
      color: '#6739b6'
    },
    {
      title: '木槿',
      name: 'mauve',
      color: '#9c26b0'
    },
    {
      title: '桃粉',
      name: 'pink',
      color: '#e03997'
    },
    {
      title: '棕褐',
      name: 'brown',
      color: '#a5673f'
    },
    {
      title: '玄灰',
      name: 'grey',
      color: '#8799a3'
    },
    {
      title: '草灰',
      name: 'gray',
      color: '#aaaaaa'
    },
    {
      title: '墨黑',
      name: 'black',
      color: '#333333'
    },
    {
      title: '雅白',
      name: 'white',
      color: '#ffffff'
    },
    ],
    openid: '',
    userInfo: null,
    period: null,
    setting: {
      signPoint: 10,
      luckTimes: 2
    }
  },

  getPeriod(callBack) {
    console.log('getPeriod')
    wx.cloud.callFunction({
      name: 'adPeriod',
      complete: res => {
        console.log(res)
        var period = res.result.data;
        wx.setStorageSync('period', period)
        this.globalData.period = period;
        callBack(period)
      }
    })
    // var a = this.globalData.period || wx.cloud.callFunction({
    //   name: 'adPeriod',
    //   complete: res => {
    //     console.log(res)
    //     var period = res.result.data;
    //     wx.setStorageSync('period', period)
    //     this.globalData.period = period;
    //     callBack(period)
    //   }
    // })
    // callBack(a)
  },

  getOpenid(callBack) {
    // let that = this;
    // console.log('come in')
    var a = this.globalData.openid || wx.cloud.callFunction({
      name: 'login',
      complete: res => {
        var openid = res.result.openid;
        wx.setStorageSync('openid', openid)
        console.log('openid: ', openid)
        // if (needInfo) this.getUserInfo1(that, openid);// 从数据库获取详细信息
        // console.log('appid: ', res.result.appid)
        this.globalData.openid = openid;
        callBack(openid)
        // that.setData({
        //   openid: openid
        // })
      }
    })
    if (a) {
      callBack(a)
    }
    // var b = this.globalData.userInfo;
    // if (b) {
    //   that.setData({
    //     userInfo: b
    //   })
    // }
    // console.log('come out'+a)
  },
  /**
   * 从数据库获取用户信息
   * @param {*} callBack 
   * @param {*} openid 
   */
  getUserInfo1: function (callBack, openid) {
    // let that = this;
    this.db.collection('userinfo').where({
      _openid: openid
    }).get().then(res => {
      if (res.data.length > 0) {
        console.log("app 查ku =")
        var user = res.data[0]
        console.log(user)
        wx.setStorageSync('userInfo', user)
        //2.存用户信息到全局变量
        this.globalData.userInfo = user
        wx.setStorageSync('isLogin', true);
        callBack(user)
      } else {
        // 无用户信息 未授权获取过
      }
    })
  },
  /**
   * 微信授权-注册getUserProfile
   * @param {*} e 
   */
  userReg(callBack) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
    // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      lang: "zh_CN",
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        // this.setData({
        //   userInfo: res.userInfo,
        //   hasUserInfo: true
        // })
        var user = res.userInfo
        console.log('app uinfo=');
        console.log(user);
        if (user) {
          console.log('读库=' + wx.getStorageSync('openid'));
          this.db.collection('userinfo').where({
            _openid: wx.getStorageSync('openid')
          }).get({
            success: olduser => {
              if (olduser.data.length > 0) {
                //1.存用户信息到本地存储
                console.log('app ku have')
                console.log(olduser.data[0])
                wx.setStorageSync('userInfo', olduser.data[0])
                //2.存用户信息到全局变量
                this.globalData.userInfo = olduser.data[0]
                wx.setStorageSync('isLogin', true);
                callBack(olduser);
              } else {
                // 新用户 注册
                //     "level":1,
                //     "point":40,
                // "income":40,
                // "spend":40,
                // "create_time":1619798400,
                // "update_time":1619798400
                // inviter 邀请者
                let time = this.nowTimeStamp();
                user.level = 1;
                user.point = 28;
                user.income = 28;
                user.spend = 0;
                if (wx.getStorageSync('inviter')) {
                  user.inviter = wx.getStorageSync('inviter')
                }
                user.create_time = time
                user.update_time = time
                console.log(user)
                wx.setStorageSync('userInfo', user)
                //2.存用户信息到全局变量
                this.globalData.userInfo = user
                wx.setStorageSync('isLogin', true);
                //授权成功后，跳转进入小程序首页
                this.db.collection('userinfo').add({
                  // data 字段表示需新增的 JSON 数据
                  data: user
                }).then(res => {
                  wx.setStorageSync('isLogin', true);

                })
                callBack(user);
              }
            },
            fail: err => {
              wx.setStorageSync('isLogin', false);
              console.log('[数据库] [查询记录] 失败：')
            }
          })
        }
      }
    })
  },
  // 获取 任务 次数
  getTaskCount: function (callBack, openid) {
    // 获取今日0点开始的时间戳
    let tday = this.stringToTime(this.formatToday());
    this.db.collection('ad_point_logs').where({
      _id: this._.exists(true),
      _openid: openid,
      create_time: this._.gte(tday)
    }).orderBy('create_time', 'desc').get({
      success: res => {
        var a = null;
        if (res.data.length > 0) {
          var signNum = 0, signTime = '', luckNum = 0;
          for (var i = 0; i < res.data.length; i++) {
            var log = res.data[i];
            if (log.type == 1) {
              signNum++;
              signTime = this.formatDateTime(log.create_time);
            }
            if (log.type == 2) luckNum++;
          }
          a = {
            signNum: signNum,
            signTime: signTime,
            luckNum: luckNum
          }
        }
        callBack(a)
      }
    })
  },
  addFans: function (callBack, openid, idol_id, point) {
    console.log("加粉丝=" + point);
    let time = this.nowTimeStamp(),
      hasvote = 0, new_hasvote = 0, fans = 0;
    var ad_user_idol =
    {
      "idol_id": idol_id,
      "hasvote": point,
      "hasdel": 0,
      "create_time": time,
      "update_time": time
    };
    this.db.collection('ad_user_idol').where({
      _openid: openid,
      idol_id: idol_id
    }).limit(1).get({
      success: res => {
        console.log(res.data);
        if (res.data.length > 0) {
          hasvote = res.data[0].hasvote || point;
          new_hasvote = hasvote + point;
          this.db.collection('ad_user_idol').where({
            _openid: openid,
            idol_id: idol_id
          }).update({
            data: {
              hasvote: new_hasvote,
              update_time: time
            },
            success: function (res) {
              callBack(res)
            }
          })
        } else {
          // 无粉丝记录
          fans = 1;
          console.log(ad_user_idol)
          this.db.collection('ad_user_idol').add({
            data: ad_user_idol
          }).then(res => {
            callBack(res)
          })
        }
        //addFans2: function (callBack, idol_id, point, fans) {
        this.addFans2(function (res) {
          console.log("刷粉回调！")
        }, idol_id, point, fans);
      }
    })
  },
  /**
   * 更新明星表
   * @param {*} callBack 
   * @param {*} idol_id 
   * @param {*} point 
   * @param {*} fans 
   */
  addFans2: function (callBack, idol_id, point, fans) {
    let time = this.nowTimeStamp(),
      old_votes = 0, votes = 0,
      old_fans = 0, new_fans = 0;
    // 加载明星信息
    this.db.collection('ad_idol').doc(idol_id).get({
      success: res => {
        var idol = res.data;
        console.log(idol);
        if (res.data) {
          console.log("bingo")
          old_votes = idol.votes || 0;
          old_fans = idol.fans || 0;
          votes = old_votes + point;
          new_fans = old_fans + fans;
          // this.db.collection('ad_idol').where({
          //   _id: idol_id
          // }).update({
          //   data: {
          //     votes: votes,
          //     fans: new_fans,
          //     update_time: time
          //   },
          //   success: function (res) {
          //     callBack(res)
          //   }
          // })
          wx.cloud.callFunction({
            name: 'dbUpdate',
            data: {
              db_name: 'ad_idol',
              where: {
                _id: idol_id
              },
              update: {
                votes: votes,
                fans: new_fans,
                update_time: time
              },
              success: res => {
                callBack(res)
              }
            }
          })
        }
      }
    })
  },
  addRank: function (callBack, idol_id, point) {
    console.log("加排行榜=" + point);
    let time = this.nowTimeStamp(),
      hasvote = 0, new_hasvote = 0, fans = 0,
      week = this.globalData.period.week,
      month = this.globalData.period.month;
    var ad_rank_week =
    {
      "idol_id": idol_id,
      "begin_time": this.globalData.period.weekBegin,
      "end_time": this.globalData.period.weekEnd,
      "week": week,
      "votes": point,
      "create_time": time,
      "update_time": time
    };
    var ad_rank_month =
    {
      "idol_id": idol_id,
      "begin_time": this.globalData.period.monthBegin,
      "end_time": this.globalData.period.monthEnd,
      "month": month,
      "votes": point,
      "create_time": time,
      "update_time": time
    };
    //1 云函数获取周期数：yyyyzzz、月期数：yyyyMM
    // 2.1 查询周榜上是否已存在
    this.db.collection('ad_rank_week').where({
      week: week,
      idol_id: idol_id
    }).limit(1).get({
      success: res => {
        console.log(res.data);
        if (res.data.length > 0) {
          // 3.1 存在，更新
          hasvote = res.data[0].votes || point;
          new_hasvote = hasvote + point;
          // this.db.collection('ad_rank_week').where({
          //   week: week,
          //   idol_id: idol_id
          // }).update({
          //   data: {
          //     votes: new_hasvote,
          //     update_time: time
          //   },
          //   success: function (res2) {
          //     // callBack(res)
          //   }
          // })
          wx.cloud.callFunction({
            name: 'dbUpdate',
            data: {
              db_name: 'ad_rank_week',
              where: {
                week: week,
                idol_id: idol_id
              },
              update: {
                votes: new_hasvote,
                update_time: time
              },
              success: res2 => {
                callBack(res)
              }
            }
          })
        } else {
          //3.2 不存在，插入
          fans = 1;
          console.log(ad_rank_week)
          this.db.collection('ad_rank_week').add({
            data: ad_rank_week
          }).then(res2 => {
            // callBack(res)
          })
        }
      }
    })
    // 2.2 查询月榜上是否已存在
    this.db.collection('ad_rank_month').where({
      month: month,
      idol_id: idol_id
    }).limit(1).get({
      success: res => {
        console.log(res.data);
        if (res.data.length > 0) {
          // 3.1 存在，更新
          hasvote = res.data[0].votes || point;
          new_hasvote = hasvote + point;
          // this.db.collection('ad_rank_month').where({
          //   month: month,
          //   idol_id: idol_id
          // }).update({
          //   data: {
          //     votes: new_hasvote,
          //     update_time: time
          //   },
          //   success: function (res2) {
          //     // callBack(res2)
          //   }
          // })
          wx.cloud.callFunction({
            name: 'dbUpdate',
            data: {
              db_name: 'ad_rank_month',
              where: {
                month: month,
                idol_id: idol_id
              },
              update: {
                votes: new_hasvote,
                update_time: time
              },
              success: res2 => {
                callBack(res)
              }
            }
          })
        } else {
          //3.2 不存在，插入
          fans = 1;
          console.log(ad_rank_month)
          this.db.collection('ad_rank_month').add({
            data: ad_rank_month
          }).then(res2 => {
            // callBack(res)
          })
        }
      }
    })
    callBack(point);
  },
  // 给用户加积分（或减积分）
  addPoint: function (callBack, openid, point) {
    console.log("加积分=" + point);
    let time = this.nowTimeStamp(),
      old_point = 0, new_point = 0,
      old_income = 0, new_income = 0;
    this.db.collection('userinfo').where({
      _openid: openid
    }).orderBy('create_time', 'desc').limit(1).get({
      success: res => {
        console.log(res.data);
        if (res.data.length > 0) {
          old_point = res.data[0].point || 0;
          old_income = res.data[0].income || 0;
          new_point = old_point + point;
          new_income = old_income;
          if (point > 0) new_income = old_income + point;
          console.log("原来: 可用=" + old_point + " 累计=" + old_income);
          console.log("之后: 可用=" + new_point + " 累计=" + new_income);
          this.db.collection('userinfo').where({
            _openid: openid
          }).update({
            // data 传入需要局部更新的数据
            data: {
              // 表示将 done 字段置为 true
              point: new_point,
              income: new_income,
              update_time: time
            },
            success: function (res) {
              callBack(res)
              // console.log(res.data){stats: {…}, errMsg: "collection.update:ok"}
            }
          })
        }
      }
    })
  },
  /**
   * 积分日志（ptype:1 签到； 2 抽奖； 3 看广告）
   * @param {*} callBack 
   * @param {*} openid 
   * @param {*} ptype 积分类型
   */
  gotPoint: function (callBack, openid, ptype, point) {
    console.log("gotPoint");
    let time = this.nowTimeStamp();
    // 除了签到、抽奖要限制次数
    this.db.collection('ad_point_logs').add({
      data: {
        type: ptype,
        create_time: time,
        point: point,
        week: this.globalData.period.week,
        month: this.globalData.period.month,
      },
      success: res => {
        //addPoint: function (callBack, openid, point)
        this.addPoint(callBack, openid, point);
        callBack(res)
      },
      fail: err => {
        callBack(res)
      }
    })
  },
  /**
   * 投票日志 外部入口
   * @param {*} callBack 
   * @param {*} openid 
   * @param {*} idol_id 
   * @param {*} point 
   */
  gotVote: function (callBack, openid, idol_id, point) {
    console.log("app 投票日志");
    let time = this.nowTimeStamp(),
      that = this;
    that.getPeriod(function (period) {
      that.db.collection('ad_vote_logs').add({
        data: {
          idol_id: idol_id,
          create_time: time,
          point: point,
          week: that.globalData.period.week,
          month: that.globalData.period.month,
        },
        success: res => {
          // this.addPoint(callBack, openid, -point);
          // callBack(res)
          that.addRank(function () {
            console.info("本期榜！");
          }, idol_id, point);
          that.addPoint(function (res2) {
            callBack(res2)
          }, openid, -point);
        },
        fail: err => {
          callBack(res)
        }
      })
    });
  },
  //////////////////////////////
  // 鉴定权限
  //判断用户权限
  authentication: function () {
    let userInfo = this.globalData.userInfo,
      admin = 0;
    if (userInfo) {
      if (userInfo.admin) {
        admin = userInfo.admin
      }
    }
    if (admin != 1) {
      wx.navigateTo({
        url: '/pages/index/index',
      })
    }
  },
  /////////////////////////////////////////
  // 时间日期类，是否可以云端获取？避免客户端时间不准确？？？？？
  // 10位时间戳转 2021-04-20 18:30:22
  formatDateTime: function (time) {
    let date = new Date(time * 1000)
    return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':' + (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes())
  },
  // 字符转时间戳
  stringToTime: function (timeString) {
    // var date = getDate(timeString)
    var date = timeString.replace(/-/g, '/');
    var timestamp = new Date(date).getTime() / 1000;
    return timestamp;
  },
  // 当前10位时间戳
  nowTimeStamp: function () {
    var timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000;
    return timestamp;
  },
  formatToday: function () {
    var timestamp = Date.parse(new Date());
    let date = new Date(timestamp)
    return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
  },

  // no##############################
  login(userInfo, success) {
    wx.cloud.callFunction({
      name: 'login',
      success: res => {
        let openid = res.result.openid
        this.db.collection('userinfo').where({
          _openid: openid
        }).get().then(res => {
          if (res.data.length > 0) {
            //更新数据并登录
            userInfo.update_time = this.getDatetime(new Date())
            this.db.collection('userinfo').where({
              _openid: openid
            }).update({
              data: userInfo,
              success: res1 => {
                for (let x in userInfo) {
                  res.data[0][x] = userInfo[x]
                }

                this.globalData.userInfo = res.data[0]
                if (typeof success == 'function') success(res.data[0])
                return
              },
              fail: err => {
                icon: 'none',
                  console.error('用户更新失败：', err)
              }
            })
          } else {
            userInfo.create_time = this.getDatetime(new Date())
            userInfo.update_time = this.getDatetime(new Date())
            this.db.collection('userinfo').add({
              data: userInfo
            }).then(res => {
              userInfo._openid = openid
              userInfo._id = res._id
              this.globalData.userInfo = userInfo
              if (typeof success == 'function') success(userInfo)
              return
            })
          }
        })
      },
      fail: err => {
        wx.showToast({
          title: '登录失败，请重试',
          icon: 'none'
        })

        return
      }
    })
  },
  //通过此方法获取用户数据
  userInfo(success, fail) {
    //先判断是否有userinfo
    if (this.globalData.userInfo) {
      if (typeof success == 'function') success(this.globalData.userInfo)
      return
    }
    //再判断是否尝试过getUserInfo接口
    if (this.globalData.getUserInfo) {
      if (typeof fail == 'function') fail()
      return
    }
    this.globalData.getUserInfo = true
    //最后尝试userInfo接口
    wx.getUserInfo({
      success: (res) => {
        this.login(res.userInfo, success)
      },
      fail(res) {
        if (typeof fail == 'function') fail()
        return
      }
    })
  }
  // ,userInfo = {}
  // ,message = []
})